import store from '../Store/index';

// 设置兼容性
// 使用 Web Audio API
const AudioContext =
  window.AudioContext ||
  window.webkitAudioContext ||
  window.mozAudioContext ||
  window.oAudioContext ||
  window.msAudioContext;

export const hasWebAudioAPI = {
  data: !!AudioContext && location.protocol.indexOf('http') !== -1
};
const music = {};
export default music;
(() => {
  if (!hasWebAudioAPI.data) {
    return;
  }

  const context = new AudioContext();
  const url_gm = './why.mp3';
  const req_gm = new XMLHttpRequest();
  req_gm.responseType = 'arraybuffer';
  req_gm.open('GET', url_gm, true);
  req_gm.onload = () => {
    context.decodeAudioData(
      req_gm.response,
      buf => {
        // 将拿到的audio解码转为buffer
        const getSource = () => {
          // 创建source源。
          const source = context.createBufferSource();
          source.buffer = buf;
          source.connect(context.destination);
          return source;
        };
        music.move = () => {
          // 移动
          if (!store.state.music) {
            return;
          }
          getSource().start(0, 1.8, 0.2437);
        };

        music.fall = () => {
          if (!store.state.music) {//用来控制事件的触发
            return;
          }
          getSource().start(0, 0.4, 1.4);
          // store.commit('musicState');
        };

        music.rotate = () => {
          // 旋转
          if (!store.state.music) {
            return;
          }
          getSource().start(0, 1.6, 0.2);
        };

        music.clear = () => {
          // 消除方块
          if (!store.state.music) {
            return;
          }
          getSource().start(0, 1, 0.4);
          getSource().start(0, 1.1, 0.5);
          getSource().start(0, 1.2, 0.6);
          getSource().start(0, 1.3, 0.7);
          getSource().start(0, 1.4, 0.8);

        };
        music.gameover = () => {
          // 游戏结束
          if (!store.state.music) {
            return;
          }
          getSource().start(0);
        };

      },
      error => {
        if (window.console && window.console.error) {
          window.console.error(`音频: ${url_gm} 读取错误`, error);
          // hasWebAudioAPI.data = false;
        }
      }
    );
  };

  req_gm.send();
})();
